#!/usr/bin/env python
# coding=utf8

import sys
import re
import urllib
import urllib2
import cookielib
from pytesser import *
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.keys import Keys
import time
import random

class GuoPeiCrack(object):
    
    def __init__(self):
        try:
            self.name = ""
            self.pwd = ""
            self.root = ""
            self.loginUrl = ""
            self.imageUrl = ""
            self.browser = ""
            self.code = ""
        except Exception,e:
            print e
        
    def setInfo(self,username,password,root,login,page):
        try:
            self.name = username
            self.pwd = password            
            self.root = root
            self.loginUrl = self.root + login
            self.page = self.root + page
            self.browser = webdriver.Ie()
        except Exception,e:
            print e
            
    def autoLogin(self):
        try:          
            self.browser.get(self.loginUrl)
            username = self.browser.find_element_by_name("txtUserName")
            username.send_keys(self.name)
            password = self.browser.find_element_by_name("txtPassWord")
            password.send_keys(self.pwd)            
            time.sleep(5)
            loginBtn = self.browser.find_element_by_name("ImgbtnLogin")
            loginBtn.click()            
        except Exception,e:
            print e            
            
    def autoClick(self):
        self.browser.get(self.page)
        startTime = 620
        endTime = 1180        
        while True:
            passedTime = random.randint(startTime,endTime)
            print "********** Time will be updated in " + str(int(passedTime/60)) + " minutes **********"
            #Wait
            time.sleep(passedTime)           
            # Auto click
            self.browser.find_element_by_xpath("//input[@value='更新学习时间']").click()
            time.sleep(5)
            self.browser.switch_to_alert().dismiss()            
            print "********** UPDATE TIME OK! **********"
            
    def getCaptain(self,imgUrl):
        try:
            image = Image.open(imgUrl)
            return image_to_string(image)
        except Exception,e:
            print e     
        
    

